package com.utilities.parsers.alignmentParser;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;

import com.utilities.parsers.alignmentParser.ParseEvents.EventTypes;

public class ParseAllContigsFileParser   
{
	private LinkedList<ParseListener> eventListeners = new LinkedList<ParseListener>();
	
	public void addListener(ParseListener parseListener)
	{
		eventListeners.add(parseListener);
	}
	
	private void fireEvent(ParseEvents parseEvent)
	{
		for (ParseListener listener : eventListeners)
		{
			listener.handleEvent(parseEvent);
		}
	}
	
	public void parse(FileReader fileReader) throws IOException
	{
		BufferedReader bufferedReader = new BufferedReader(fileReader);
		fireEvent(new ParseEvents(null,EventTypes.docStarted));
		String readLine = bufferedReader.readLine();
		while(!readLine.startsWith("========="))
		{
			readLine = bufferedReader.readLine();
		}
		fireEvent(new ParseEvents(readLine, EventTypes.headerMarker));
		readLine = bufferedReader.readLine();
		fireEvent(new ParseEvents(readLine,EventTypes.alignedSequencesInfo));
		readLine = bufferedReader.readLine();
		while(readLine != null)
		{
			if (readLine.contains("BEGIN alignment"))
			{
				fireEvent(new ParseEvents(readLine,EventTypes.beginAlignment));
			}
			else if (readLine.contains("END alignment"))
			{
				fireEvent(new ParseEvents(readLine, EventTypes.endAlignment));
			}
			else if (readLine.trim().startsWith("==================="))
			{
			}
			else if (readLine.trim().length() != 0 && !readLine.contains("^"))
			{
				fireEvent(new ParseEvents(readLine,EventTypes.referenceSeq));
				readLine = bufferedReader.readLine();
				fireEvent(new ParseEvents(readLine,EventTypes.querySeq));
			}
			readLine = bufferedReader.readLine();
		}
		fireEvent(new ParseEvents(null,EventTypes.docEnded));
	}
	
	public void removeAllListeners()
	{
		eventListeners.clear();
	}
}
